﻿using Furion;
using Furion.Converters.Json;
using Furion.VirtualFileServer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Text.Encodings.Web;
using System.Text.Json.Serialization;
using System.Text.Json;
using System.Text.Unicode;
using tlBasic.Core;
using Yitter.IdGenerator;
using System;
using Microsoft.Extensions.Logging;

namespace tlBasic.Web.Core
{
    public class Startup : AppStartup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddConfigurableOptions<DbConnectionOptions>();
            services.AddJwt<JwtHandler>(enableGlobalAuthorize: true);
            //配置跨域
            services.AddCors(cor =>
            {
                cor.AddPolicy("Cors", policy =>
                {
                    policy
                    .AllowAnyOrigin()
                    .AllowAnyHeader()
                    .AllowAnyMethod();
                });
            });


            // ORM-SqlSugar
            services.AddSqlSugarSetup(); 
            services.AddCorsAccessor();
            services.AddControllersWithViews() 
                      .AddInjectWithUnifyResult<RstRProvider>()
                .AddJsonOptions(options =>
                {
                    options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
                    options.JsonSerializerOptions.NumberHandling = JsonNumberHandling.AllowReadingFromString;
                    options.JsonSerializerOptions.ReadCommentHandling = JsonCommentHandling.Skip;
                    options.JsonSerializerOptions.AllowTrailingCommas = true;
                    options.JsonSerializerOptions.PropertyNamingPolicy = null;
                    options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
                    options.JsonSerializerOptions.Converters.AddDateTimeTypeConverters("yyyy-MM-dd HH:mm:ss");
                    options.JsonSerializerOptions.Converters.Add(new IntJsonConverter());
                    options.JsonSerializerOptions.Converters.Add(new LongJsonConverter());
                    options.JsonSerializerOptions.Converters.Add(new DecimalJsonConverter());
                    options.JsonSerializerOptions.Converters.Add(new StringJsonConverter()); 
                });
            services.Configure<FormOptions>(x =>
            {
                x.ValueLengthLimit = int.MaxValue;
                x.MultipartBodyLengthLimit = int.MaxValue; // In case of multipart
            });
            services.Configure<IISServerOptions>(x =>
            {
                x.AllowSynchronousIO = true;
            });
            services.AddEventBus();

          
            services.AddMonitorLogging();

            // 日志写入文件-调试、消息、警告、错误
            Array.ForEach(new[] { LogLevel.Debug, LogLevel.Information, LogLevel.Warning, LogLevel.Error }, logLevel =>
            {
                services.AddFileLogging("logs/{0:yyyyMMdd}/" + $"{logLevel}.log", options =>
                {
                    options.FileNameRule = fileName => string.Format(fileName, DateTime.Now); // 每天创建一个文件
                    options.WriteFilter = logMsg => logMsg.LogLevel == logLevel;
                    options.FileSizeLimitBytes = 10 * 1024 * 1024;
                    options.MaxRollingFiles = 30;
                });
            });

            // 设置雪花Id算法机器码
            YitIdHelper.SetIdGenerator(new IdGeneratorOptions
            {
                WorkerId = 9
            });
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCorsAccessor();
            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseInject();
            app.UseUnifyResultStatusCodes();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}